package com.chuangke.project.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.chuangke.admin.data.builder.DeptDataBuilder;
import com.chuangke.admin.data.builder.UserDataBuilder;
import com.chuangke.common.constant.CacheKeyConstants;
import com.chuangke.common.data.builder.DataBuildConfig;
import com.chuangke.common.data.builder.DataBuilder;
import com.chuangke.common.db.page.CkPageQuery;
import com.chuangke.common.db.page.PageUtil;
import com.chuangke.common.utils.CollectionUtils;
import com.chuangke.project.dao.ProjectMapper;
import com.chuangke.project.model.Project;
import com.chuangke.project.service.ProjectService;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class ProjectServiceImpl implements ProjectService {
    @Autowired
    private ProjectMapper projectMapper;

    @Override
    public void saveOrUpdate(Project project) {
        Project a = findById(project.getId());
        if (a == null) {
            ((ProjectService) AopContext.currentProxy()).save(project);
        } else {
            ((ProjectService) AopContext.currentProxy()).update(project);
        }
    }

    @CacheEvict(cacheNames = CacheKeyConstants.BS_PROJECT, key = "'" + CacheKeyConstants.BS_PROJECT + "'")
    @Override
    public void save(Project project) {
        projectMapper.insert(project);
    }

    @Cacheable(cacheNames = CacheKeyConstants.BS_PROJECT, key = "'" + CacheKeyConstants.BS_PROJECT + "'")
    @Override
    public Map<String, Project> findAll() {
        List<Project> list = projectMapper.selectList(Wrappers.emptyWrapper());
        DataBuilder.of(list)
                .appendBuilder(new UserDataBuilder(), new DataBuildConfig("createdBy", "createdBy"),
                        new DataBuildConfig("updatedBy", "updatedBy"))
                .appendBuilder(new DeptDataBuilder(), new DataBuildConfig("deptId", "deptName")).build();
        return list.stream().collect(Collectors.toMap(Project::getId, a -> a));
    }

    @CacheEvict(cacheNames = CacheKeyConstants.BS_PROJECT, key = "'" + CacheKeyConstants.BS_PROJECT + "'")
    @Override
    public void update(Project project) {
        projectMapper.updateById(project);
    }

    public Project findById(String id) {
        Map<String, Project> map = ((ProjectService) AopContext.currentProxy()).findAll();
        return map.get(id);
    }

    @Override
    public IPage<Project> page(CkPageQuery page) {
        Map<String, Project> map = ((ProjectService) AopContext.currentProxy()).findAll();
        List<Project> projectList = new ArrayList<>(map.values());
        String label = (String) page.get("name");
        projectList = projectList.stream()
                .filter(dict -> ((StrUtil.isEmpty(label)
                        || (StrUtil.isNotEmpty(label) && dict.getName().matches(".*" + label + ".*"))
                        || (StrUtil.isNotEmpty(label) && (dict.getId() + "").matches(".*" + label + ".*")))))
                .collect(Collectors.toList());
        String status = (String) page.get("status");
        projectList = projectList.stream()
                .filter(dict -> ((StrUtil.isEmpty(status)
                        || (StrUtil.isNotEmpty(status) && status.equals(dict.getStatus())))))
                .collect(Collectors.toList());
        String deptId = (String) page.get("deptId");
        projectList = projectList.stream()
                .filter(dict -> ((StrUtil.isEmpty(deptId)
                        || (StrUtil.isNotEmpty(deptId) && deptId.equals(dict.getDeptId())))))
                .collect(Collectors.toList());
        projectList = projectList.stream().sorted((a, b) -> CollectionUtils.compare(a.getId() + "", b.getId() + "")).collect(Collectors.toList());
        return PageUtil.findPage(page, projectList);
    }

    @CacheEvict(cacheNames = CacheKeyConstants.BS_PROJECT, key = "'" + CacheKeyConstants.BS_PROJECT + "'")
    @Override
    public void changeStatus(List<String> idList, String status) {
        //停用之前判断是否已被使用
        for (String s : idList) {
            Project project = new Project();
            project.setStatus(status);
            project.setId(s);
            projectMapper.updateById(project);
        }
    }

}
